import {
  Controller,
  Post,
  Body,
  Get,
  UseGuards,
  Request,
  Res,
  HttpStatus,
} from '@nestjs/common';
import { Response } from 'express';
import { AuthService } from './auth.service';
import { LoginDto } from './dto/login.dto';
import { RegisterDto } from './dto/register.dto';
import { JwtAuthGuard } from './guards/jwt-auth.guard';
import * as svgCaptcha from 'svg-captcha';

@Controller('auth')
export class AuthController {
  private captchaStore = new Map<string, { code: string; expires: number }>();

  constructor(private readonly authService: AuthService) {
    // 定期清理过期验证码
    setInterval(() => {
      const now = Date.now();
      for (const [key, value] of this.captchaStore.entries()) {
        if (value.expires < now) {
          this.captchaStore.delete(key);
        }
      }
    }, 60000); // 每分钟清理一次
  }

  @Post('register')
  async register(@Body() registerDto: RegisterDto) {
    return this.authService.register(registerDto);
  }

  @Post('login')
  async login(@Body() loginDto: LoginDto) {
    return this.authService.login(loginDto);
  }

  @Post('email-code/send')
  async sendEmailCode(@Body() body: { email: string }) {
    return this.authService.sendEmailCode(body.email);
  }

  @Post('email-code/login')
  async loginWithEmailCode(
    @Body() body: { email: string; code: string },
  ) {
    return this.authService.loginWithEmailCode(body.email, body.code);
  }

  @Get('captcha')
  getCaptcha(@Res() res: Response) {
    const captcha = svgCaptcha.create({
      size: 4, // 验证码长度
      noise: 2, // 干扰线条数
      color: true, // 验证码字符是否有颜色
      background: '#f0f0f0', // 背景颜色
      width: 120,
      height: 40,
    });

    // 生成唯一ID
    const captchaId = `captcha_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    
    // 存储验证码（5分钟过期）
    this.captchaStore.set(captchaId, {
      code: captcha.text.toLowerCase(),
      expires: Date.now() + 5 * 60 * 1000,
    });

    res.json({
      captchaId,
      captchaSvg: captcha.data,
    });
  }

  @Post('captcha/verify')
  verifyCaptcha(@Body() body: { captchaId: string; code: string }) {
    const stored = this.captchaStore.get(body.captchaId);
    
    if (!stored) {
      return { valid: false, message: '验证码已过期' };
    }

    if (stored.expires < Date.now()) {
      this.captchaStore.delete(body.captchaId);
      return { valid: false, message: '验证码已过期' };
    }

    const isValid = stored.code === body.code.toLowerCase();
    
    if (isValid) {
      this.captchaStore.delete(body.captchaId); // 验证后删除
    }

    return {
      valid: isValid,
      message: isValid ? '验证成功' : '验证码错误',
    };
  }

  @UseGuards(JwtAuthGuard)
  @Get('profile')
  getProfile(@Request() req) {
    return req.user;
  }
}

